package icantalk.voip;

import java.math.BigInteger;

/**
 * Class used for some heplful conversions
 *
 * @author Antonín Brettšnajdr
 */
public class Conversions {

    public static byte[] LongTo16bitPCMbyte(long[] l) {
        byte[] b = new byte[l.length * 2];
        BigInteger bi;
        byte[] tb;
        long val;

        for (int i = 0; i < b.length; i += 2) {
            val = l[i / 2];
            bi = BigInteger.valueOf(val);
            tb = bi.toByteArray();

            if (tb.length == 1) {
                b[i] = tb[0];

                if (val < 0) {
                    b[i + 1] = (byte) -1;
                } else {
                    b[i + 1] = (byte) 0;
                }
            } else {
                b[i] = tb[1];
                b[i + 1] = tb[0];
            }

        }

        return b;

    }


    public static long[] PCM16bitByteToLong(byte[] b) {
        long[] l = new long[b.length / 2];

        for (int i = 0; i < l.length; i++) {
            l[i] = new BigInteger(new byte[]{b[i * 2 + 1], b[i * 2]}).longValue();
        }

        return l;
    }
}
